# -*- coding: utf-8 -*-

import os
import webapp2
from google.appengine.ext.webapp import template
from models import getRelevantInfo


# Including the models:
from models.getRelevantInfo import *

# We are using django's simplejson
# module to format JSON strings:
from django.utils import simplejson
import json
import cgi

#importing for google calendar
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import datetime

#importing google calendar libs
import atom
import gdata.service
import gdata.auth
import gdata.alt.appengine
import gdata.calendar
import gdata.calendar.service


import logging

from google.appengine.api import urlfetch

# This controller handles the
# generation of the front page.
 
class MainHandler(webapp2.RequestHandler):
        def __init__(self, request, response):
                self.initialize(request, response)
                urlfetch.set_default_fetch_deadline(55)
                # Create a Google Calendar client to talk to the Google Calendar service.
                self.calendar_client = gdata.calendar.service.CalendarService()
                # Modify the client to search for auth tokens in the datastore and use
                # urlfetch instead of httplib to make HTTP requests to Google Calendar.
                gdata.alt.appengine.run_on_appengine(self.calendar_client)
        
        def get(self):
           
            
            
            #We are using the template module to output the page.
            self.template_file = 'pop_up_templates.html'
            isCalendar = self.request.get('token')
            token_request_url = ''
            isSuccess = ''    
            if not isinstance(self.calendar_client.token_store.find_token(
                          'http://www.google.com/calendar/feeds/'),
                          gdata.auth.AuthSubToken):
                      token_request_url = gdata.auth.generate_auth_sub_url(self.request.uri,
                         ['http://www.google.com/calendar/feeds/default/'],False,True)
            
              
            
            if(isCalendar is not ""):
                  #to be placed when the site goes up - in main?
                  #checkAccessToGoogleCalendar._init_(self)
            
            
                  # Find an AuthSub token in the current URL if we arrived at this page from
                  # an AuthSub redirect.
                  auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)
                  if auth_token:
                      self.calendar_client.SetAuthSubToken(
                          self.calendar_client.upgrade_to_session_token(auth_token))
                      isSuccess = 'yes'
                  # Check to see if the app has permission to write to the user's
                  # Google Calendar.
                  
            else:
              isSuccess = 'no'
                  
            template_values = {
                      'calendarAccess': token_request_url,
                      'syncName': isSuccess
                  }
            
            path = os.path.join(os.path.dirname(__file__), '../views' ,self.template_file)
            self.response.out.write(
            
              # The render method takes the path to a html template,
              # and a dictionary of key/value pairs that will be
              # embedded in the page.
              template.render( path,template_values ))
        
        def post(self):
                jsonToSyncData = json.loads(cgi.escape(self.request.body))
                
                if(jsonToSyncData[0]=='createEvent'):
                        exam = jsonToSyncData[1]
                        
                        edit_link_to_send_back = -1
                        
                        date = exam[0]
                        name = exam[1]
                        color = exam[2]
                        number = exam[3]
                        moed = exam[4]
                        type1 = exam[5]
                        #examBeginHourStr = exam[7]
                        #examEndHourStr = exam[8]
                        
                        semester = ''
                        if(int(exam[6]) == 0):
                                semester = u'סמסטר א'
                        else:
                                semester = u'סמסטר ב'
                                
#                         if(examBeginHourStr == u'---'):
#                                 examBeginHourStr = u''
                        
#                         if(examEndHourStr == u'---'):
#                                 examEndHourStr = u''
                                
                        event_entry = gdata.calendar.CalendarEventEntry()
                        
                        event_entry.title = atom.Title(text = type1+u': '+name+u' (מועד '+moed+u') - '+semester)
                        #event_entry.content = atom.Content(text = name+u' ('+number+u') - '+semester+u'\n'+type1+u', מועד '+moed+u'\n'+examBeginHourStr+u'-'+examEndHourStr)
                        event_entry.content = atom.Content(text = name+u' ('+number+u') - '+semester+u'\n'+type1+u', מועד '+moed+u'\n'+u'\n'+u'אנא התעדכן לגבי שעת התחלה ושעת סיום מול גורם אוניברסיטאי.'+u'\n'+u'\n'+u'אירוע זה נוצר ע"י מערכת bid-it.')
                        #create date
                        year = None
                        month = None
                        day = None
                        dateDMY = None
                        dateDMY = date.split('/')
                        year = int(dateDMY[2])+2000
                        month = int(dateDMY[1])
                        day = int(dateDMY[0])
                        
                        #makes it +3 hours, so if there is a time, should be 3 hours less.
                        #temporary_date = datetime.datetime.strptime(date , '%Y-%m-%d')
#                         examBeginHourInt = None
#                         examBeginMintsInt = None
#                         examBeginHourStrHoursMints = []
                        #if the begin hour is empty, start at 5+3=8
#                         if(examBeginHourStr == u''):
#                                 examBeginHourInt = 5
#                                 examBeginMintsInt = 0
                        #else, split to mints and hours
#                         else:
#                                 examBeginHourStrHoursMints = examBeginHourStr.split(':')
#                                 #if the begin hour's hour starts with zero - delete the zero
#                                 if(int(examBeginHourStrHoursMints[0][0]) == 0):
#                                         examBeginHourInt = int(examBeginHourStrHoursMints[0][1])
#                                 #else take all the number
#                                 else:
#                                         examBeginHourInt = int(examBeginHourStrHoursMints[0])
#                                 #if the begin hour's mints starts with zero - delete the zero
#                                 if(int(examBeginHourStrHoursMints[1][0]) == 0):
#                                         examBeginMintsInt = int(examBeginHourStrHoursMints[1][1])
#                                 #else take all the number
#                                 else:
#                                         examBeginMintsInt = int(examBeginHourStrHoursMints[1])
                        
                        
                        #startTimeTemp = datetime.datetime(year,month,day,examBeginHourInt,examBeginMintsInt,0,0,None)
                        startTimeTemp = datetime.datetime(year,month,day,1,0,0,0,None)
                        #startTimeTemp = datetime.date(year,month,day)
                        #start_time = datetime.date(year,month,day)
                        start_time = '%s.000Z' % startTimeTemp.isoformat()
                        
                        
#                         examEndHourInt = None
#                         examEndMintsInt = None
#                         examEndHourStrHoursMints = []
                        #if the begin hour is empty, end at examBeginHourInt
#                         if(examEndHourStr == u''):
#                                 examEndHourInt = examBeginHourInt+1
#                                 examEndMintsInt = 0
                        #else, split to mints and hours
#                         else:
#                                 examEndHourStrHoursMints = examEndHourStr.split(':')
#                                 #if the end hour's hour starts with zero - delete the zero
#                                 if(int(examEndHourStrHoursMints[0][0]) == 0):
#                                         examEndHourInt = int(examEndHourStrHoursMints[0][1])
#                                 #else take all the number
#                                 else:
#                                         examEndHourInt = int(examEndHourStrHoursMints[0])
#                                 #if the end hour's mints starts with zero - delete the zero
#                                 if(int(examEndHourStrHoursMints[1][0]) == 0):
#                                         examEndMintsInt = int(examEndHourStrHoursMints[1][1])
#                                 #else take all the number
#                                 else:
#                                         examEndMintsInt = int(examEndHourStrHoursMints[1])
                        #endTimeTemp = datetime.datetime(year,month,day,examEndHourInt,examEndMintsInt,0,0,None)
                        endTimeTemp = datetime.datetime(year,month,day,20,0,0,0,None)
                        #endTimeTemp = datetime.date(year,month,day)
                        end_time = '%s.000Z' % endTimeTemp.isoformat()
                        
                        
                        event_entry.when.append(gdata.calendar.When(start_time=start_time,end_time=end_time))
                        #event_entry.where.append(gdata.calendar.Where(value_string=' '))
                   
                        # Send the event information to Google Calendar and receive a
                        # Google Calendar event.
                        try:
                                cal_event = self.calendar_client.InsertEvent(event_entry,
                                                                             'http://www.google.com/calendar/feeds/default/private/full')
                                edit_link = cal_event.GetEditLink()
                                if edit_link and edit_link.href:
                                        # Add the edit link to the event to use for making changes.
                                        edit_link_to_send_back = edit_link.href
                        except gdata.service.RequestError, request_exception:
                                request_error = request_exception[0]
                                if request_error['status'] == 401 or request_error['status'] == 403:
                                    #or request_error['status'] == 302
                                        gdata.alt.appengine.save_auth_tokens({})
                                # If the request failure was not due to a bad auth token, reraise the
                                # exception for handling elsewhere. - return -1
        #                         else:
        #                                 raise
                        
                        
                        msg = type1+u': '+name+u' (מועד '+moed+u') - '+semester
                        jsonOptStr = json.dumps({
                        "response"  : edit_link_to_send_back,
                        "msg" : msg
                        })
                        
                        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
                        self.response.write(jsonOptStr)
                
                #jsonToSyncData[0]=='deleteEvent'
                else:
                        jsonOptStr = json.dumps({
                        "response"  : '1'
                        })
                        linkToDelete = jsonToSyncData[1]
                        try:
                                self.calendar_client.DeleteEvent(str(linkToDelete))
                        
                        except gdata.service.RequestError, request_exception:
                                request_error = request_exception[0]
                                if request_error['status'] == 401 or request_error['status'] == 403:
                                        jsonOptStr = json.dumps({
                                        "response"  : 'event not found in google calendar'
                                        })
                        
                        
                        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
                        self.response.write(jsonOptStr)